package com.github.xzb617.utils;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

/**
 * @author xzb617
 * @date 2022/5/16 8:45
 * @description:
 */
public class CollectionUtil {

    public static List arrayToList(Object source) {
        if (source == null) {
            throw new IllegalArgumentException("source can not null");
        }
        return Arrays.asList(toObjectArray(source));
    }

    private static Object[] toObjectArray(Object source) {
        if (source instanceof Object[]) {
            return (Object[])((Object[])source);
        } else if (source == null) {
            return new Object[0];
        } else if (!source.getClass().isArray()) {
            throw new IllegalArgumentException("Source is not an array: " + source);
        } else {
            int length = Array.getLength(source);
            if (length == 0) {
                return new Object[0];
            } else {
                Class<?> wrapperType = Array.get(source, 0).getClass();
                Object[] newArray = (Object[])((Object[])Array.newInstance(wrapperType, length));

                for(int i = 0; i < length; ++i) {
                    newArray[i] = Array.get(source, i);
                }

                return newArray;
            }
        }
    }

}
